using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Globalization;

namespace SmartLink.DTOS.JsonSettings
{
    /// <summary>
    /// 自定义时间类型Json转换器
    /// </summary>
    public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter() { }
        public CustomDateTimeConverter(string format)
        {
            DateTimeFormat = format;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                DateTime result;
                var success = DateTime.TryParse(reader.Value.ToString(), out result);
                if (success)
                    return result;
                else
                    throw new JsonSerializationException($"不支持的时间参数格式。({reader.Path + ":" + reader.Value})");
            }
            return base.ReadJson(reader, objectType, existingValue, serializer);

        }
    }
    /// <summary>
    /// 默认的日期类型Json转换器（yyyy-MM-dd）
    /// </summary>
    public class DefaultDateConverter : CustomDateTimeConverter
    {
        public DefaultDateConverter() : base("yyyy-MM-dd") { }
    }
    /// <summary>
    /// 默认的年月类型Json转换器（yyyy-MM）
    /// </summary>
    public class DefaultYearMonthConverter : CustomDateTimeConverter
    {
        public DefaultYearMonthConverter() : base("yyyy-MM") { }
    }
}
